package com.example.backend.service.impl;

import com.example.backend.service.EmailService;
import com.example.backend.service.EmailLogService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring6.SpringTemplateEngine;

import java.io.File;
import java.util.Map;

/**
 * 邮件服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {
    
    private final JavaMailSender mailSender;
    private final SpringTemplateEngine templateEngine;
    private final EmailLogService emailLogService;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @Override
    @Async
    public void sendSimpleMail(String to, String subject, String content) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            log.info("简单邮件发送成功");
        } catch (Exception e) {
            log.error("发送简单邮件时发生异常！", e);
            throw new RuntimeException("邮件发送失败", e);
        }
    }
    
    @Override
    @Async
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            log.info("HTML邮件发送成功");
        } catch (MessagingException e) {
            log.error("发送HTML邮件时发生异常！", e);
            throw e;
        }
    }
    
    @Override
    @Async
    public void sendAttachmentsMail(String to, String subject, String content, 
            Map<String, File> attachments) throws MessagingException {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            
            // 添加附件
            for (Map.Entry<String, File> entry : attachments.entrySet()) {
                FileSystemResource file = new FileSystemResource(entry.getValue());
                helper.addAttachment(entry.getKey(), file);
            }
            
            mailSender.send(message);
            log.info("带附件的邮件发送成功");
        } catch (MessagingException e) {
            log.error("发送带附件的邮件时发生异常！", e);
            throw e;
        }
    }
    
    @Override
    @Async
    public void sendTemplateMail(String to, String subject, String template, 
            Map<String, Object> variables) throws MessagingException {
        String content = null;
        try {
            // 创建邮件正文
            Context context = new Context();
            variables.forEach(context::setVariable);
            content = templateEngine.process(template, context);
            
            // 发送邮件
            this.sendHtmlMail(to, subject, content);
            
            // 记录成功日志
            emailLogService.recordEmailLog(to, subject, content, template, true, null);
            
            log.info("模板邮件发送成功");
        } catch (Exception e) {
            // 记录失败日志
            emailLogService.recordEmailLog(to, subject, content, template, false, e.getMessage());
            
            log.error("发送模板邮件时发生异常！", e);
            throw e;
        }
    }
} 